package com.sky.controller.admin;/**
 * @author with葡萄成熟时
 * @version 1.0
 */

import com.sky.config.OssConfiguration;
import com.sky.constant.MessageConstant;
import com.sky.result.Result;
import com.sky.utils.AliOssUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

/**
 * @ClassName CommonController
 * @Description 公共类相关接口
 * @Author Wait葡萄成熟时
 * @Date 2024/11/5 下午9:06
 * @Version 1.0
 */
@RestController
@Slf4j
@Api(tags = "公共类相关接口")
public class CommonController {

    //OssConfiguration配置类中的一个方法加入了bean容器中，并且它返回了一个对象AliOssUtil，用的就是这个对象
    @Autowired
    private AliOssUtil aliOssUtil;

    @ApiOperation("文件上传")
    @PostMapping("/admin/common/upload")
    public Result<String> upload(@RequestParam("file") MultipartFile file) {


        // 避免文件覆盖
        String originalFilename = file.getOriginalFilename();
        String fileName = UUID.randomUUID().toString() + originalFilename.substring(originalFilename.lastIndexOf("."));

        //上传文件到 OSS
        try {
            String filePath = aliOssUtil.upload(file.getBytes(), fileName);
            return Result.success(filePath);
        } catch (IOException e) {

            log.error("上传失败", e.getMessage());
        }

        return Result.error(MessageConstant.UPLOAD_FAILED);
    }


}
